<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <!-- <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="5" :offset="0">
                    <el-form-item label="日志类型">
                        <el-select v-model="searchForm.logType" placeholder="请选择">
                            <el-option v-for="item in options_logType" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form> -->

        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="出发打卡" name="first">
                <el-table 
                    :data="tableData1" 
                    stripe 
                    style="width: 100%" 
                    :row-style="{ height: '60px' }">
                    <el-table-column label="打卡人" align="center" width="200">
                        <template #default="{ row }">
                            {{ row.engineerName }}
                        </template>
                    </el-table-column>
                    <el-table-column label="打卡位置" align="center" show-overflow-tooltip>
                        <template #default="{ row }">
                            {{ row.formattedAddress }}
                        </template>
                    </el-table-column>
                    <el-table-column label="打卡时间" align="center" width="200">
                        <template #default="{ row }">
                            {{ dateFormatter(row.createTime) }}
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="工单日志" name="second">
                <el-table :data="tableData" stripe style="width: 100%" :row-style="{ height: '60px' }"
                    v-loading="tableDataLoading">
                    <el-table-column label="日志类型" align="center" width="130">
                        <template #default="{ row }">
                            {{ formatLogType(row.logType) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="日志内容" align="center" show-overflow-tooltip>
                        <template #default="{ row }">
                            {{ row.logContent }}
                        </template>
                    </el-table-column>
                    <el-table-column label="日志图片" align="center">
                        <template #default="{ row }">
                            <span v-if="row.photos">
                                <span v-for="(item, index) in row.photos.split(',')" :key="index">
                                    <el-image :z-index="8000" style="width: 60px; height: 60px; margin-left: 5px;" :src="item"
                                        :preview-src-list="row.photos.split(',')" preview-teleported />
                                </span>
                            </span>
                            <span v-else>无</span>
                        </template>
                    </el-table-column>

                    <!-- <el-table-column label="上班时间" align="center">
                        <template #default="{ row }">
                            {{ dateFormatter(row?.dataForClockIn && row?.dataForClockIn[0]?.createTime)}}
                        </template>
                    </el-table-column>

                    <el-table-column label="下班时间" align="center">
                        <template #default="{ row }">
                            {{ dateFormatter(row?.dataForClockOut && row?.dataForClockOut[0]?.createTime) }}
                        </template>
                    </el-table-column> -->

                    <el-table-column label="操作时间" align="center" width="200">
                        <template #default="{ row }">
                            {{ dateFormatter(row.createTime) }}
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" align="center" width="250">
                        <template #default="{ row }">
                            <div>
                                <el-button v-if="row && row.logId" type="primary" size="small" text @click="updateLogCreateTimePre(row)">修改操作时间</el-button>
                                <el-button v-if="row && row.logId" type="primary" size="small" text @click="lookSignInfo(row)">查看打卡信息</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

        <!-- 分页组件 -->
        <!-- <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="searchForm.total"
                :current-page="searchForm.page" :page-size="searchForm.size" @current-change="getData" />
        </div> -->
    </el-card>

    <el-dialog v-model="dialogVisible_updateTime" title="修改操作时间" width="500">
        <el-date-picker value-format="YYYY-MM-DDTHH:mm:ss" v-model="logUpdateTimeBody.createTime" type="datetime" placeholder="选择时间" />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible_updateTime = false">取消</el-button>
                <el-button type="primary" @click="updateLogCreateTime">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 打开信息table -->
    <el-dialog v-model="dialogVisible_signInfo" title="查看打卡时间" width="1000">
        <el-table :data="signInfoTableData" stripe :border="true">
            <el-table-column label="打卡人" align="center" width="130">
                <template #default="{ row }">
                    {{ row.clockInPerson }}
                </template>
            </el-table-column>

            <el-table-column label="上班时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.clockInTime)}}
                </template>
            </el-table-column>

            <el-table-column label="打卡位置" align="center" width="200">
                <template #default="{ row }">
                    {{ row.clockInAddress }}
                </template>
            </el-table-column>

            <el-table-column label="下班时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.clockOutTime)}}
                </template>
            </el-table-column>

            <el-table-column label="打卡位置" align="center" width="200">
                <template #default="{ row }">
                    {{ row.clockOutAddress }}
                </template>
            </el-table-column>
        </el-table>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible_signInfo = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>

import { onMounted, ref, reactive } from "vue";
import { api_orders_log_location, api_orders_log_updateCreateTime, api_orders_getLogByOrderId } from "~/api/ordersApi";
import { toast, toastWarn } from "~/composables/util";
import { dateFormatter } from "~/utils/common";


const options_logType = [{ value: 1, label: '施工前拍照检查' }, { value: 2, label: '施工计划' }, { value: 3, label: '每日工作日志' }, { value: 4, label: '施工结束拍照' }]

//父子传参，orderDetail：工单详情
const props = defineProps({
    orderDetail: Object
})

//tab页
const activeName = ref('first')

//出发打卡
const tableData1 = ref([])

//工单日志
const tableDataLoading = ref(false)
const searchForm = reactive({
    orderId: null,
    // logType: null,
    // page: 1,
    // size: 5,
    // total: null
})
const tableData = ref([])
const dialogVisible_updateTime = ref(false)
const logUpdateTimeBody = reactive({})
const setOutClockIn = ref(null) // 出发打卡信息

//打卡信息弹窗
const dialogVisible_signInfo = ref(false)
const signInfoTableData = ref([])

onMounted(() => {
    //工单ID
    searchForm.orderId = props.orderDetail.orderId
    //加载出发打卡时间
    getSetOutClockIn()
    //工单日志列表
    getData()
})

const handleClick = (tab, event) => {
    console.log(tab, event)
}


// 查询工单日志
const getData = (e) => {
    if (typeof (e) == 'number') {
        searchForm.page = e
    }
    let reqBody = {
        orderId: searchForm.orderId,
        // logType: searchForm.logType,
        // page: searchForm.page,
        // size: searchForm.size,
    }
    api_orders_getLogByOrderId(reqBody).then(res => {
        // console.log('tableData.value ', tableData.value)
        tableData.value = res
        // tableData.value = tableData.value.concat(res)
        // searchForm.total = res.total
        // searchForm.page = res.current
    })
}

// 出发打卡信息
const getSetOutClockIn = () => {
    let reqBody = {
        orderId: props.orderDetail.orderId,
        locationType: 4,
    }
    api_orders_log_location(reqBody).then(res => {
        //console.log('query order log location 0: ', res)
        //setOutClockIn.value = res?.records[0]
        // tableData1.value = [{
        //     logType: '出发打卡',
        //     logContent: '出发打卡',
        //     logAddress: res?.records[0].formattedAddress,
        //     createTime: res?.records[0].createTime
        // }, ...tableData.value ]
        if(res && res.records){
            tableData1.value = res.records
            console.log('tableData1.value', JSON.stringify(tableData1.value))
        }else{
            tableData1.value = []
        }
        
        //console.log('table data :', tableData.value)
    })
}

// 重置按钮
const resetSearchForm = () => {
    searchForm.logType = null
    searchForm.page = 1
    searchForm.size = 5
    searchForm.total = null
}

// 日志类型
const formatLogType = (state) => {
    return options_logType.find(x => x.value == state)?.label || state
}

// 更新操作时间 前置
const updateLogCreateTimePre = (row) => {
    dialogVisible_updateTime.value = true 
    logUpdateTimeBody.logId = row.logId
    logUpdateTimeBody.createTime = ''
}

// 查看打卡信息
const lookSignInfo = (row) => {

    //构建打卡table数据
    let dataList = []

    //1、先找出两个集合的engineerId并集
    let engineerIds = new Set();
    if(null != row.dataForClockIn){
        row.dataForClockIn.forEach(obj => {
            engineerIds.add(obj.engineerId);
        });
    }
    if(null != row.dataForClockOut){
        row.dataForClockOut.forEach(obj => {
            engineerIds.add(obj.engineerId);
        });
    }
    //console.log("engineerIds--------->",engineerIds,engineerIds.size)
    //2、遍历set构建数据
    if(null != engineerIds && engineerIds.size > 0){
        engineerIds.forEach((item) => {
            let json = {}
            //上班打卡
            if(null != row.dataForClockIn){
                const obj = row.dataForClockIn.filter(o => o.engineerId == item);
                if(null != obj && obj.length>0){
                    json.clockInPerson = obj[0].engineerName
                    json.clockInTime = obj[0].createTime
                    json.clockInAddress = obj[0].formattedAddress
                }else{
                    json.clockInPerson = null
                    json.clockInTime = null
                    json.clockInAddress = "-"
                }
            }else{
                json.clockInPerson = null
                json.clockInTime = null
                json.clockInAddress = "-"
            }
            //下班打卡
            if(null != row.dataForClockOut){
                const obj = row.dataForClockOut.filter(o => o.engineerId == item);
                if(null != obj && obj.length>0){
                    if(json.clockInPerson == null){
                        json.clockInPerson = obj[0].engineerName
                    }
                    json.clockOutTime = obj[0].createTime
                    json.clockOutAddress = obj[0].formattedAddress
                }else{
                    json.clockOutTime = "-"
                    json.clockOutAddress = "-"
                }
            }else{
                json.clockOutTime = null
                json.clockOutAddress = "-"
            }
            dataList.push(json)
        });
    }

    //3、赋值
    signInfoTableData.value = dataList
    //4、打开弹窗
    dialogVisible_signInfo.value = true 
}


// 更新操作时间
const updateLogCreateTime = () => {
    if (!logUpdateTimeBody?.createTime) {
        toastWarn('选择操作时间')
        return
    }
    console.log('logUpdateTimeBody', logUpdateTimeBody)
    api_orders_log_updateCreateTime(logUpdateTimeBody).then(res => {
        toast("修改操作时间成功")
        dialogVisible_updateTime.value = false
        getData()
    })
}
</script>